#include "../inc/write_mblog_widget.h"
#include <QTextDocument>

write_mblog_widget::write_mblog_widget(QWidget *parent)
    : QWidget(parent)
{
	ui.setupUi(this);
	this->my_parent=parent;
	this->ReplyMblogGuid=0;
	this->SetSoftKeys();
}

write_mblog_widget::~write_mblog_widget()
{

}

void write_mblog_widget::SetSoftKeys(){
	QAction* actReturn = new QAction(tr("Back"), this);
	actReturn->setSoftKeyRole(QAction::NegativeSoftKey);
	addAction(actReturn);
	connect(actReturn, SIGNAL(triggered()), this, SLOT(OnSkReturn()));
	QAction* actAdd = new QAction(tr("add"), this);
	actAdd->setSoftKeyRole(QAction::PositiveSoftKey);
	addAction(actAdd);
	connect(actAdd, SIGNAL(triggered()), this, SLOT(OnSkAdd()));
}

void write_mblog_widget::OnSkAdd(){
	QString con=this->ui.tbContent->toPlainText();
	if(con.length()>MblogLength){
		QMessageBox::critical(this,
								  "error",
								  "limit in "+QString(MblogLength)+" alphas",
								  QMessageBox::Ok);
		return;
	}
	QString hl=this->ui.cbHideLocation->isChecked()?"0":"1";
	QString sp=this->ui.cbSetPrivacy->isChecked()?"1":"0";
	QString lat(_BUPT_LATITUDE_);
	QString lon(_BUPT_LONGITUDE_);
	QString xml=XmlHEADER+
			"<mblog>"+
                        "<content>"+Qt::escape(con)+"</content>"+
			"<location>"+
			"<latitude>"+lat+"</latitude>"+
			"<longitude>"+lon+"</longitude>"+
			"<visible>"+hl+"</visible>"+
			"</location>"+
			"<private>"+sp+"</private>"+
			"</mblog>";
	QUrl u(AddMblogUrl);
	u.addQueryItem("token",QUrl::toPercentEncoding(dt::Token()));
	#ifdef _USE_MID_PAGE_
	QString _u=u.toString();
	u=QUrl(_MID_PAGE_);
	u.addQueryItem("url",QUrl::toPercentEncoding(_u));
	#endif
	dh=new DtHttp(u,POST,this,xml.toUtf8());
	connect(dh->Send(),SIGNAL(finished(QNetworkReply*)),this,SLOT(finished(QNetworkReply*)));
}

void write_mblog_widget::OnSkReturn(){
	this->my_parent->showMaximized();
	this->~write_mblog_widget();
}

void write_mblog_widget::finished(QNetworkReply *reply){
    if(reply->error() == QNetworkReply::NoError)
    {
		QString xml=reply->readAll();
		dt::Set(reply->url().toString(),xml);
		this->ReadXml(xml);
    }
    else
    {
		QMessageBox::critical(this,
								  "error",
								  "network fail",
								  QMessageBox::Ok);
		return;
    }
}

void write_mblog_widget::ReadXml(const QString& xml){
	QDomDocument doc("mydocument"); 
	if (!doc.setContent(xml,false)) 
	{        
		QMessageBox::critical(this,
							  "error",
							  "network fail",
							  QMessageBox::Ok);  
		return;      
	}
	QDomElement ele;
    QDomElement docElem = doc.documentElement(); 
	QDomElement eleEr=docElem.firstChildElement("error");
	ele=eleEr.firstChildElement("code");
	if(ele.text().trimmed()=="1"){
		QString desc=eleEr.firstChildElement("desc").text();
		QMessageBox::critical(this,
							  "fail",
							  desc,
							  QMessageBox::Ok);  
		return;  
	}
	ele=docElem.firstChildElement("guid");
	int g=ele.text().toInt();
}
